<?php

namespace app\model;

use app\model\Base\ApijsonLog as BaseApijsonLog;

class ApijsonLog extends BaseApijsonLog
{
    /**
     * 创建APIJSON日志记录
     *
     * @param array $data
     * @return ApijsonLog
     */
    public static function createLog(array $data): ApijsonLog
    {
        return self::create($data);
    }

    /**
     * 获取用户最近的APIJSON调用记录
     *
     * @param string $userId
     * @param string $userType
     * @param int $limit
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getUserRecentLogs(string $userId, string $userType = 'admin', int $limit = 50)
    {
        return self::where('user_id', $userId)
            ->where('user_type', $userType)
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }

    /**
     * 获取APIJSON端点调用统计
     *
     * @param string|null $spaceId
     * @param int $days
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getEndpointStats(?string $spaceId = null, int $days = 7)
    {
        $query = self::where('created_at', '>=', now()->subDays($days));
        
        if ($spaceId) {
            $query->where('space_id', $spaceId);
        }

        return $query->selectRaw('
            endpoint,
            caller_type,
            COUNT(*) as call_count,
            AVG(execution_time) as avg_execution_time,
            MAX(execution_time) as max_execution_time,
            SUM(CASE WHEN is_success = 1 THEN 1 ELSE 0 END) as success_count,
            SUM(CASE WHEN is_success = 0 THEN 1 ELSE 0 END) as error_count,
            SUM(record_count) as total_records
        ')->groupBy('endpoint', 'caller_type')
        ->orderBy('call_count', 'desc')
        ->get();
    }

    /**
     * 获取APIJSON性能统计
     *
     * @param string|null $spaceId
     * @param int $days
     * @return array
     */
    public static function getPerformanceStats(?string $spaceId = null, int $days = 7): array
    {
        $query = self::where('created_at', '>=', now()->subDays($days));
        
        if ($spaceId) {
            $query->where('space_id', $spaceId);
        }

        return $query->selectRaw('
            COUNT(*) as total_calls,
            AVG(execution_time) as avg_execution_time,
            MAX(execution_time) as max_execution_time,
            MIN(execution_time) as min_execution_time,
            AVG(memory_usage) as avg_memory_usage,
            MAX(memory_usage) as max_memory_usage,
            SUM(record_count) as total_records,
            SUM(CASE WHEN is_success = 1 THEN 1 ELSE 0 END) as success_count,
            SUM(CASE WHEN is_success = 0 THEN 1 ELSE 0 END) as error_count
        ')->first()->toArray();
    }

    /**
     * 获取调用方类型统计
     *
     * @param string|null $spaceId
     * @param int $days
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function getCallerTypeStats(?string $spaceId = null, int $days = 7)
    {
        $query = self::where('created_at', '>=', now()->subDays($days));
        
        if ($spaceId) {
            $query->where('space_id', $spaceId);
        }

        return $query->selectRaw('
            caller_type,
            COUNT(*) as call_count,
            AVG(execution_time) as avg_execution_time,
            SUM(record_count) as total_records
        ')->groupBy('caller_type')
        ->orderBy('call_count', 'desc')
        ->get();
    }

    /**
     * 清理过期日志
     *
     * @param int $days
     * @return int
     */
    public static function cleanExpiredLogs(int $days = 30): int
    {
        return self::where('created_at', '<', now()->subDays($days))->delete();
    }
}

